package org.ngbx.springboot.demo.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.ngbx.springboot.demo.controller.KafkaMessage;
import org.ngbx.springboot.demo.infrastructure.constant.KafkaConstant;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
@Slf4j
public class MessageHandler {
    @Resource
    private ObjectMapper objectMapper;

    @KafkaListener(topics = KafkaConstant.TEST_TOPIC)
    public void handleMessage(ConsumerRecord<String, byte[]> record, Acknowledgment acknowledgment) {
        try {
            KafkaMessage message = objectMapper.readValue(record.value(), KafkaMessage.class);
            log.info("收到消息: {}", message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            // 手动提交 offset
            acknowledgment.acknowledge();
        }
    }
}
